<template>
    <!-- 新闻查看 -->
    <div class="news">
        <div class="left">
            <div class="operation">
                <div class="search">
                    <el-input v-model="input" @keyup.enter.native="search" placeholder="请输入搜索内容" clearable />
                    <el-select v-model="selectValue" class="m-2" multiple collapse-tags collapse-tags-tooltip
                        placeholder="Select" style="margin-left: 5px; width: 70%;">
                        <el-option v-for="item in options" :key="item.id" :label="item.type" :value="item.id" />
                    </el-select>
                    <el-button style="margin-left: 10px; margin-right: 10px;" type="primary" @click="search"
                        :icon="Search">搜索&重置</el-button>
                </div>
                <div style="display: flex;">
                    <el-button style="margin-right: 10px;" type="danger" v-if="store.user.organizationId <= 2"
                        @click="showDiaLog('删除种类')">删除种类</el-button>
                    <span></span>
                    <el-button style="margin-right: 10px;" type="primary" v-if="store.user.organizationId <= 2"
                        @click="showDiaLog('添加种类')">添加种类</el-button>
                    <span></span>
                    <el-button type="primary" @click="mysearch">我的文章</el-button>


                </div>

            </div>
            <el-scrollbar height="100%" v-loading="loading">
                <TransitionGroup tag="ul" name="list">
                    <div v-if="news_data?.list.length != 0" class="container" v-for="(item, index) in news_data?.list"
                        :key="item.id">
                        <div style="width: 100%;display: flex;justify-content: space-between; align-items: center;">
                            <div class="user">
                                <div>
                                    <img class="imga" :src="item.userImageUrl" />
                                </div>
                                <div class="details">
                                    <div class="name">{{ item.name }}</div>
                                    <div class="date"><span> {{ time(new Date(item.createdAt))
                                    }}</span></div>
                                </div>
                            </div>
                            <div class="deletes" v-if="store.user.organizationId <= 2 || item.userId == store.user.id"
                                @click="deleteNews(item.id, index)">
                                删除
                            </div>
                        </div>

                        <div class="title">{{ item.title }}</div>
                        <div class="content" v-html="item.content"></div>
                        <!-- <div class="imgas"> <img v-for=" image in  item.imageUrl " :src="image" alt=""></div> -->
                        <div class="useopen">
                            评论<img src="@/assets/image/评论.png" @click="showComment(item.id)" alt="">
                            <span></span>
                            <img @click="nwesLike(item.likeStatus, item.id, index)" v-if="item.likeStatus"
                                src="@/assets/image/点赞_块.png" alt="">
                            <img v-else @click="nwesLike(item.likeStatus, item.id, index)" src="@/assets/image/点赞.png"
                                alt="">{{
                                    item.likeCount
                                }}
                        </div>
                    </div>
                    <div v-else>没有文章，快去发布一个吧！</div>
                </TransitionGroup>
            </el-scrollbar>
        </div>
        <div class="right">
            <Transition name="fade">
                <div class="bockcor" v-show="!commentShow">
                    <div class="h2">
                        飙升榜
                    </div>
                    <el-scrollbar height="100%">
                        <div class="rankingList" v-for="item, index in rankingList">
                            <div>{{ index + 1 }}</div>
                        
                                <div class="texte" @click="idNews(item.id, item.title)">
                                    {{ item.title }}
                                </div>
                         

                            <div>
                                新增点赞数：{{ item.increaseCount }}
                            </div>
                        </div>
                    </el-scrollbar>
                </div>
            </Transition>
            <div v-show="commentShow" class="comt">
                <Comment :id=commentId></Comment>
            </div>
        </div>
        <el-pagination class="pagination" v-model:current-page="current_page" background layout="prev, pager, next"
            @current-change="currentChange" :total="news_data?.pageCount! * 10" />

        <teleport to="body">
            <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
                <el-input v-model="input2" placeholder="请输入种类" />
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="setKind()">
                            确认
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </teleport>
    </div>
</template>

<script lang="ts">
export default { name: 'news' };
</script>
<script lang="ts" setup>
import { ref, reactive, nextTick, onActivated } from "vue"
import { newsList, optionsList, likeMessage, deletLike, likeSoaring, addKind, deleteKind, deleteMessage, pagePersonalMessage } from '@/request/api'
import { time } from '@/hooks/index'
import Comment from "./comment.vue"
import type { news_data, opliset, likeDatum, List } from '@/type/news'
import { ElNotification, ElMessage } from 'element-plus'
import {
    Search
} from '@element-plus/icons-vue'
import { useStore } from '@/stores/counter'
import { useRoute } from "vue-router"
let current_page = ref(0)

const route = useRoute()
const store = useStore()
let news_data = ref<news_data>()
let selectValue = ref<number[]>([])       //分类详情
const options = reactive<opliset[]>([])      //分类集合
let input = ref<string>("")         //搜索内容
let pageIndex = ref<number>(0)            //当前页数
let loading = ref<boolean>(false)         //loading动画
//文章获取函数
interface newsBody {
    keyword: string
    kinds: number[],
    pageIndex: string | number
    pageSize: string | number
}
const requestNews = (index: number) => {
    loading.value = true
    return newsList<newsBody>({ "keyword": input.value, "kinds": selectValue.value, "pageIndex": index, "pageSize": 6 }).then(res => {
        news_data.value = res.data
        nextTick(() => {
            loading.value = false
        })
        return Promise.resolve("成功")
    })

}
onActivated(() => {
    if (route.query.id) {
        idNews(+route.query.id, route.query.name as string)
    } else if (route.query.set) {
        requestNews(0)
        current_page.value = 1
    }
})


//点击飙升榜或者点击数据图获得精准的文章 
const requestac = async (name: string, id: Number, pageIndex: number, arr: any):Promise<List[]> => {
    let Lists: List[] = []
    await newsList<newsBody>({
        "keyword": name,
        "kinds": arr,
        "pageIndex": pageIndex,
        "pageSize": 6
    }).then(res => {
        //过滤得到最终的
        Lists.push(...res.data.list)
        if (res.data.list.length >= 6) {
            requestac(name, id, pageIndex + 1, arr)
        }

    })
    return Lists
}
const idNews =async (id: number, name: string) => {
    loading.value = true
    news_data.value!.list.length = 0
    let arr = options.reduce((e: number[], net) => {
        e.push(net.id)
        return e
    }, [])
    let Lists: List[] =[]
     await requestac(name, id, 0, arr).then(res=>{
        Lists.push(...res)
    })
    news_data.value?.list.push(...Lists.filter((e) => {
        return e.id == id
    }))
    nextTick(() => {
        loading.value = false
    })
}
//获取初始文章
const requestOption = () => {
    optionsList().then(res => {
        options.length = 0
        selectValue.value.length = 0
        options.push(...res.data)
        selectValue.value.push(res.data[0].id)
        requestNews(0)
    })
}
requestOption()
//分页
const currentChange = (e: number) => {
    pageIndex.value = e
    requestNews(e)
}
//搜索
const search = () => {
    pageIndex.value = 0
    current_page.value = 1
    requestNews(pageIndex.value).then(res => {
        ElNotification({
            title: '成功',

            type: 'success',
        })
        input.value = ''
    })
}
//查看个人文章
const mysearch = () => {
    loading.value = true
    current_page.value = 1
    pagePersonalMessage({ "keyword": input.value, "kinds": selectValue.value, "pageIndex": 0, "pageSize": 6 }).then(res => {
        news_data.value = res.data
        setTimeout(() => {
            loading.value = false
        }, 500)
    })
}
//打开评论
let commentShow = ref<boolean>(false)
let commentId = ref<number>(-1)           //打开评论的页面id
const showComment = (id: number) => {
    commentId.value = id
    commentShow.value = true
}


//点赞
const nwesLike = (type: number, id: number, index: number) => {
    if (Boolean(type)) {
        deletLike<number>(id).then(res => {

            news_data.value!.list[index].likeStatus = 0
            news_data.value!.list[index].likeCount -= 1
        })
    } else
        likeMessage<number>(id).then(res => {

            news_data.value!.list[index].likeStatus = 1
            news_data.value!.list[index].likeCount += 1


        })
}

//飙升榜数据
let rankingList = reactive<likeDatum[]>([])
const requestrankingList = () => {
    likeSoaring().then(res => {

        rankingList.length = 0
        rankingList.push(...res.data)
    })
}
requestrankingList()

//种类操作
let dialogVisible = ref(false)
let input2 = ref('')
let dialogTitle = ref('删除种类')
const setKind = () => {
    (
        dialogTitle.value == '删除种类' ? deleteKind(input2.value).then(res => {
            return res.data ? Promise.resolve(res.data) : Promise.reject(res.msg)
        }) : addKind(input2.value).then(res => {
            return res.data ? Promise.resolve(res.data) : Promise.reject(res.msg)
        })
    ).then((res: string) => {
        dialogVisible.value = false
        requestOption()
        nextTick(() => {
            ElMessage({
                message: res,
                type: 'success',
            })
        })
    }).catch(err => {
        ElMessage.error(err)
    })
}
const showDiaLog = (title: string) => {
    dialogTitle.value = title
    dialogVisible.value = true
}

//删除新闻
const deleteNews = (id: number, index: number) => {
    deleteMessage([id]).then(res => {

        ElMessage({
            showClose: true,
            message: res.data,
            type: 'success',
        })
        news_data.value?.list.splice(index, 1)
        requestrankingList()
    })
}
</script>

<style lang=less  scoped>
.news {
    display: flex;
    flex-wrap: wrap;
    padding: 2vw;
    box-sizing: border-box;


}

.comt {
    width: 100%;
    height: 100%;
}

/* 1. 声明过渡效果 */
.list-enter-active,
.list-leave-active {
    transition: all 0.5s ease;
}

.list-leave-active {
    position: absolute;
}

.list-leave-to,
.list-enter-from {
    opacity: 0;
    transform: translateX(100%);
}

.fade-leave-active {
    position: absolute;
}

.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}

.pagination {
    width: 100%;
    height: 8%;
    display: flex;
    margin-top: 10px;
    justify-content: end;
    border-top: 1px solid rgba(151, 148, 148, 0.562);
}

.operation {
    .flexAc();
    flex-wrap: wrap;
    justify-content: space-between;
    margin-bottom: 2vh;
    padding-bottom: 1vh;
    flex: 1;

    // border-bottom: 1px solid rgba(151, 148, 148, 0.562);
    >div {
        margin: 5px 0px;
    }

    .search {
        flex: 1;
        min-width: 55%;
        .flexAc();

    }
}

.left {
    width: 60%;
    height: 90%;
    display: flex;
    color: @color;
    flex-direction: column;
}

.right {
    width: 35.5%;
    padding-left: 2%;
    position: relative;
    margin-left: 2%;
    border-left: 1px solid rgba(185, 185, 185, 0.418);
    height: 90%;
    color: @color;

    .comments {
        position: absolute;
    }

    .bockcor {
        width: calc(100% - 4.2%);
        height: 100%;
        position: absolute;

        border-radius: 20px;

    }
}

.container {
    padding-bottom: 3vh;
    margin-bottom: 5vh;
    border-bottom: 1px solid rgba(206, 206, 206, 0.411);
    overflow: hidden;
    color: @color;

    .useopen {
        text-align: right;
        margin-top: 1vh;
        .flexAc();
        font-size: 0.4vw;
        justify-content: flex-end;

        img {
            width: 1vw;
            aspect-ratio: 1/1;
            margin: 0px .2vw;
            cursor: pointer;
        }

        span {
            margin-left: 3vw;
        }
    }

    .imgas {
        width: 100%;
        display: flex;
        flex-wrap: wrap;

        img {
            width: 45%;
            margin-right: 5%;
            aspect-ratio: 2/1.5;
            object-fit: cover;
            margin-top: 1vh;
        }
    }

    .content {
        margin-top: 1vh;

    }

    .title {
        margin-top: 1vh;
        font-size: px;

    }

    .user {
        display: flex;
        align-items: center;

        .imga {
            background-color: aqua;
            border-radius: 50%;
            width: 50px;
            aspect-ratio: 1/1;
        }

        .details {
            margin-left: 0.5vw;

            .name {
                font-size: 0.8vw;
                font-weight: 600;
            }




            .date {
                font-size: 0.5vw;

                color: rgb(88, 88, 88);
            }

        }
    }
}

.deletes {
    font-size: 0.8vw;
    cursor: pointer;
}

.deletes::after {
    content: ' ';
    display: block;
    height: 1px;
    background-color: #000;
    transition: all 0.3s ease-in-out;
    transform: scale(0);
    transform-origin: left;

}

.deletes:hover::after {
    transform: scale(1);
}

.h2 {
    font-size: 1.2vw;
    font-weight: 600;
    text-align: center;
    margin-bottom: 1vh;
}

.rankingList {
    width: 100%;
    padding-top: 1vh;
    height: fit-content;
    padding-bottom: 1vh;
    .flexAc();
    justify-content: space-between;
    border-radius: 2%;
    margin-bottom: 1vh;
    border-bottom: .5px solid #e0e0e07c;

    .texte::after {
        content: ' ';
        display: block;
        height: 1px;
        background-color: #000;
        transition: all 0.3s ease-in-out;
        transform: scale(0);
        transform-origin: left;

    }

    .texte:hover::after {
        transform: scale(1);
    }

    .texte {
        cursor: pointer;
        display: inline-block;
        flex: 1;
        .textNOLine();
        width: 100%;
        margin-left: 2vw;
        margin-right: 1vw;

    }
}

// .rankingList:hover{
// background-color: rgba(219, 219, 219, 0.603);
// }
</style>